package org.oschina.api.discuss.tag.dao;

import java.util.ArrayList;
import java.util.List;
import org.oschina.Constants;
import org.oschina.api.BaseDAO;
import org.oschina.api.discuss.tag.model.DiscussTag;
import org.oschina.api.discuss.tag.vo.DiscussTagVo;
import org.springframework.stereotype.Repository;

@Repository
public class DiscussTagDAO extends BaseDAO {

	private final String findVo[]={"id","content"};
	
	private final String findVoByDiscuss="SELECT dt.id as 'id',dt.content as 'content',(SELECT COUNT(*) FROM "+Constants.DB_DISCUSS_TAG+" WHERE content=dt.content) as 'count' FROM "+Constants.DB_DISCUSS_TAG+" dt WHERE dt.discuss=?";
	/**
	 * 根据讨论返回
	 * @param discuss
	 * @return
	 */
	public List<DiscussTagVo> findVoByDiscuss(int discuss)
	{
		if(isNeedCacheByDiscuss(discuss))
		{
			return getQueryHelper().query_cache(Constants.CACHE_DISCUSS_TAG, Constants.TIMEOUT_DISCUSS_TAG, 
					findVoByDiscuss, new Object[]{discuss}, DiscussTagVo.class);
		}
		
		return getQueryHelper().query(findVoByDiscuss, new Object[]{discuss}, DiscussTagVo.class);
	}
	private boolean isNeedCacheByDiscuss(int id)
	{
		return getCacheHelper().exists(this.getKey(Constants.CACHE_DISCUSS,id));
	}
	
	private final String findByDiscussForum="SELECT dt.id as 'id',dt.content as 'content',COUNT(dt.content) as 'count' FROM "+Constants.DB_DISCUSS_TAG+" dt,"+Constants.DB_DISCUSS+" ds WHERE dt.discuss=ds.id AND ds.forum=? GROUP BY dt.content ORDER BY count DESC LIMIT ?,?";
	/**
	 * 根据板块返回
	 * @param forum
	 * @param first
	 * @param max
	 * @return
	 */
	public List<DiscussTagVo> findByVoDiscussForum(int forum,int first,int max)
	{
		return getQueryHelper().query_cache(Constants.CACHE_DISCUSS_TAG, Constants.TIMEOUT_DISCUSS_TAG, findByDiscussForum,
				new Object[]{forum,first,max}, DiscussTagVo.class);
	}
	
	/**
	 * 批量创建
	 * @param discussTags
	 * @return
	 */
	public int[] batchCreate(List<DiscussTag> discussTags)
	{
		List<Object[]> args=new ArrayList<Object[]>(discussTags.size());
		for(DiscussTag discussTag:discussTags)
			args.add(new Object[]{discussTag.getId(),discussTag.getDiscuss(),discussTag.getContent(),discussTag.getCreate_time()});
		return getQueryHelper().batchUpdate("INSERT "+Constants.DB_DISCUSS_TAG+"(id,discuss,content,create_time) VALUES(?,?,?,?)", args);
	}
}